/**
 * 描述: 业务逻辑处理 - 任务相关接口
 * 作者: Jack Chen
 * 日期: 2020-06-20
 */

const wechat = require('../utils/wechat')
const jwt = require('jsonwebtoken');
const boom = require('boom');
const sha1 = require("sha1");
var sign = require('../utils/sign.js');
const {
    appID,
    url
} = require('../config')
const {
    CODE_ERROR,
    CODE_SUCCESS,
    PRIVATE_KEY,
    JWT_EXPIRED
} = require('../utils/constant');
const {
    decode
} = require('../utils/user-jwt');


//调用微信API接口
async function shareConfig(url) {
    return new Promise(async resolve => {
        //需要ticket,noncestr(随机字符串),timestamp(时间戳),url(当前服务器地址)
        const { ticket } = await wechat.fetchTicket();
        //生成随机字符串
        const noncestr = Math.random().toString(36).substring(2, 15);
        const timestamp = parseInt(new Date().getTime() / 1000) + '';
        //组合
        const arr = [`jsapi_ticket=${ticket}`, `noncestr=${noncestr}`, `timestamp=${timestamp}`, `url=${url}`];
        const signature = sha1(arr.sort().join("&"));
        resolve({ signature, noncestr, timestamp });
    })
}


// 添加任务
async function addTask(req, res, next) {
    const urlconfig = `${url}/api${req.url}`
    console.log(urlconfig);
    //url需要从请求那里拿，在拼上域名，这样保证不会出错，
    const { signature, noncestr, timestamp } = await shareConfig(urlconfig);
    res.render("search", { appID, signature, noncestr, timestamp, url })
}

// 获取签名
async function getSignture(req, res, next) {
    const urlconfig = req.body.url;
    console.log(urlconfig);
    //url需要从请求那里拿，在拼上域名，这样保证不会出错，
    const { signature, noncestr, timestamp } = await shareConfig(urlconfig);
    res.json({ appID, signature, noncestr, timestamp, url })
}

module.exports = {
    addTask,
    getSignture
}